//
//  FavoriteViewController.m
//  FlickrSearching
//
//  Created by HOCVIEN on 4/25/15.
//  Copyright (c) 2015 HOCVIEN. All rights reserved.
//

#import "FavoriteViewController.h"

@interface FavoriteViewController ()
@property (strong, nonatomic) NSArray* favoriteList;
@property (strong, nonatomic) NSArray *allTableData;
@property (strong, nonatomic) NSMutableArray *fillterTableData;
@property BOOL isSearching;
@end

@implementation FavoriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.favoriteTableView.delegate = self;
    self.favoriteTableView.dataSource = self;
    self.favoriteSearchBarDisplay.searchResultsDataSource =self;
    self.favoriteSearchBarDisplay.searchResultsDelegate = self;
    
    _favoritesSearchBar.delegate = self;
    
    _fillterTableData = [[NSMutableArray alloc]init];
    
    if (_photoID == nil) {
        _photoID = @"1253576";
    }
    [self.activityView setHidden:NO];
    [self.favoritesActivityIndicator startAnimating];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:124/256.0f green:70/256.0f blue:134/256.0 alpha:1];
    
    UILabel* title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"Favorites";
    title.font = [UIFont fontWithName:@"Tahoma" size:20.0f];
    title.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = title;
    
    [FlickrHelper getFavoriteWithPhotoId:_photoID callback:^(NSArray *result, NSError *error) {
        if (!error) {
            _favoriteList = result;
            _allTableData = result;
            //NSLog(@"%@",_favoriteList);
            [self.favoriteTableView reloadData];
            [self.favoritesActivityIndicator stopAnimating];
            
        }
        else{
            NSLog(@"Load data error Message: %@",error);
            [self.favoritesActivityIndicator stopAnimating];
        }
        
        [self.activityView setHidden:YES];
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString* identifier = @"Cell";
    FavoriteTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        [tableView registerClass:[FavoriteTableViewCell class] forCellReuseIdentifier:identifier];
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    }
    
    NSMutableDictionary *favoriteDetails;
    if (self.isSearching) {
        cell = [self.favoriteTableView dequeueReusableCellWithIdentifier:identifier];
        
        favoriteDetails = _fillterTableData[indexPath.row];

    }
    else{
        //NSLog(@"ABC");
        favoriteDetails = _favoriteList[indexPath.row];
        
    }
    
    cell.favoriteName.text = favoriteDetails[@"username"];
    NSTimeInterval interval = [favoriteDetails[@"favedate"] doubleValue];
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"HH:mm - dd/MM/yyyy"];
    NSString* dateStr = [dateFormat stringFromDate:date];
    dateStr = [dateStr stringByReplacingOccurrencesOfString:@"-" withString:@"on"];
    cell.favoriteDates.text = dateStr;
    cell.textLabel.text = nil;
    cell.detailTextLabel.text = nil;
    
    if (indexPath.row%2 == 0) {
        cell.backgroundColor = [UIColor colorWithRed:247/256.0f green:238/256.0f blue:249/256.0f alpha:1];
    }
    else{
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isSearching) {
        return _fillterTableData.count;
    }
    return _favoriteList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSString *identifier = @"Cell";
    //FavoriteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    return 62;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma UISearchBarController

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (searchText.length > 0) {
        self.isSearching = YES;
        [self searchTableList];
    }
    else{
        self.isSearching = NO;
    }
    
    [self.favoriteTableView reloadData];
}

-(void)searchTableList{
    NSString* searchString = self.favoritesSearchBar.text;
    [_fillterTableData removeAllObjects];
    //NSDictionary* tempDic = _allTableData;
    int i = 0;
    for (NSDictionary* tempDic in _allTableData) {
        //NSLog(@"%d ",i);
        if ([tempDic[@"username"] rangeOfString:searchString].location != NSNotFound) {
            [_fillterTableData addObject: tempDic];
            
        }
        i++;
    }
    
    if (_fillterTableData.count == 0) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Search result" message:@"Search result is null!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
    }
    
    [self.favoriteTableView reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self searchTableList];
    self.isSearching = NO;
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    self.isSearching = NO;
    [_fillterTableData removeAllObjects];
    [self.favoriteTableView reloadData];
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    self.isSearching = NO;
    [_fillterTableData removeAllObjects];
    [self.favoriteTableView reloadData];
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
